import React, { useState, useEffect } from 'react';
import { Layout, Button, Empty, Spin, message, Modal } from 'antd';
import { PlusOutlined, CloudUploadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import ProjectCard from '../components/system/ProjectCard';
import ProjectForm from '../components/system/ProjectForm';
import ImportModal from '../components/system/ImportModalV2';
import { projectApi } from '../services/api';
import { Project, ProjectCreate, ProjectUpdate } from '../types';

const { Content } = Layout;

const ProjectList: React.FC = () => {
  const navigate = useNavigate();
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [formVisible, setFormVisible] = useState(false);
  const [editingProject, setEditingProject] = useState<Project | undefined>();
  const [deletingProject, setDeletingProject] = useState<Project | undefined>();
  const [importModalVisible, setImportModalVisible] = useState(false);

  // 加载项目列表
  const loadProjects = async () => {
    try {
      setLoading(true);
      const data = await projectApi.getProjects();
      // 按 sort_order 降序排序（数字越大越靠前），如果 sort_order 相同则按创建时间排序
      const sortedProjects = [...data].sort((a, b) => {
        if (a.sort_order !== b.sort_order) {
          return b.sort_order - a.sort_order;
        }
        return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
      });
      setProjects(sortedProjects);
    } catch (error) {
      console.error('Failed to load projects:', error);
      message.error('加载项目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProjects();
  }, []);

  // 创建项目
  const handleCreateProject = async (values: ProjectCreate): Promise<boolean> => {
    try {
      // 确保 sort_order 有默认值
      const projectData: ProjectCreate = {
        ...values,
        sort_order: values.sort_order ?? 0
      };
      const newProject = await projectApi.createProject(projectData);
      // 添加新项目后重新加载列表以保持排序
      loadProjects();
      setFormVisible(false);
      return true;
    } catch (error) {
      console.error('Failed to create project:', error);
      message.error('创建项目失败');
      return false;
    }
  };

  // 更新项目
  const handleUpdateProject = async (values: ProjectUpdate): Promise<boolean> => {
    if (!editingProject) return false;
    
    try {
      const sortOrder = values.sort_order !== undefined ? values.sort_order : editingProject.sort_order;

      const newStart = (values as any).start_year ?? editingProject.start_year;
      const newEnd = (values as any).end_year ?? editingProject.end_year;
      const newStep = (values as any).year_step ?? editingProject.year_step;

      const timeChanged = (
        newStart !== editingProject.start_year ||
        newEnd !== editingProject.end_year ||
        newStep !== editingProject.year_step
      );

      const applyNonTimeUpdate = async (baseNameEn: string) => {
        const nonTimeUpdate: ProjectUpdate = {
          name: values.name ?? editingProject.name,
          name_en: values.name_en ?? editingProject.name_en,
          description: values.description ?? editingProject.description,
          sort_order: sortOrder,
        };
        return projectApi.updateProjectByName(baseNameEn, nonTimeUpdate);
      };

      if (timeChanged) {
        const oldLen = editingProject.time_horizon;
        const newLen = Math.floor((newEnd - newStart) / newStep) + 1;

        const doYearRangeUpdate = async () => {
          await projectApi.updateProjectYearRangeByName(editingProject.name_en, {
            start_year: newStart,
            end_year: newEnd,
            year_step: newStep,
          });
          // 年份更新后再更新非时间字段（如有变化）
          await applyNonTimeUpdate(editingProject.name_en);
        };

        if (newLen === oldLen) {
          await doYearRangeUpdate();
        } else if (newLen > oldLen) {
          await new Promise<void>((resolve, reject) => {
            Modal.confirm({
              title: '长度变化提示',
              content: `有效年份长度将从 ${oldLen} 变为 ${newLen}，新增部分将使用默认值填充。是否继续？`,
              okText: '继续',
              cancelText: '取消',
              onOk: async () => {
                try {
                  await doYearRangeUpdate();
                  resolve();
                } catch (e) { reject(e as any); }
              },
              onCancel: () => reject(new Error('USER_CANCELLED')),
              centered: true,
            });
          });
        } else {
          await new Promise<void>((resolve, reject) => {
            Modal.confirm({
              title: '长度变短警告',
              content: `有效年份长度将从 ${oldLen} 变为 ${newLen}，多余数据将被删除。是否继续？`,
              okText: '继续',
              cancelText: '取消',
              okButtonProps: { danger: true },
              onOk: async () => {
                try {
                  await doYearRangeUpdate();
                  resolve();
                } catch (e) { reject(e as any); }
              },
              onCancel: () => reject(new Error('USER_CANCELLED')),
              centered: true,
            });
          });
        }
      } else {
        await applyNonTimeUpdate(editingProject.name_en);
      }

      await loadProjects();
      setEditingProject(undefined);
      setFormVisible(false);
      return true;
    } catch (error: any) {
      if (error && (error.message === 'USER_CANCELLED' || error.message === '用户取消')) {
        // 用户主动取消，不提示错误
        return false;
      }
      console.error('Failed to update project:', error);
      message.error('更新项目失败');
      return false;
    }
  };

  // 删除项目
  const handleDeleteProject = async () => {
    if (!deletingProject) return;
    
    try {
      await projectApi.deleteProjectByName(deletingProject.name_en);
      setProjects(prev => prev.filter(p => p.id !== deletingProject.id));
      setDeletingProject(undefined);
      message.success('项目删除成功');
    } catch (error) {
      console.error('Failed to delete project:', error);
      message.error('删除项目失败');
    }
  };

  // 查看项目详情
  const handleViewProject = (project: Project) => {
    navigate(`/project/${project.name_en}`);
  };

  // 编辑项目
  const handleEditProject = (project: Project) => {
    setEditingProject(project);
    setFormVisible(true);
  };

  // 删除项目确认
  const handleDeleteConfirm = (project: Project) => {
    setDeletingProject(project);
  };

  // 表单提交
  const handleFormSubmit = async (values: ProjectCreate | ProjectUpdate): Promise<boolean> => {
    if (editingProject) {
      return await handleUpdateProject(values as ProjectUpdate);
    } else {
      return await handleCreateProject(values as ProjectCreate);
    }
  };

  // 关闭表单
  const handleFormCancel = () => {
    setFormVisible(false);
    setEditingProject(undefined);
  };

  return (
    <Layout>
      <Content>
        <div className="page-header">
          <div className="header-content">
            <div className="header-left">
              <h1 className="page-title">参数管理系统</h1>
              <p className="page-description">管理您的项目参数</p>
            </div>
            <div className="header-actions">
              <Button
                icon={<CloudUploadOutlined />}
                onClick={() => setImportModalVisible(true)}
                style={{ marginRight: 12 }}
                size="large"
              >
                导入项目
              </Button>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => setFormVisible(true)}
                size="large"
              >
                新建项目
              </Button>
            </div>
          </div>
        </div>

        <div className="page-content">
          {loading ? (
            <div className="loading-container">
              <Spin size="large" />
            </div>
          ) : projects.length === 0 ? (
            <Empty
              description="暂无项目"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            >
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={() => setFormVisible(true)}
              >
                创建第一个项目
              </Button>
            </Empty>
          ) : (
            <div className="projects-grid">
              {projects.map(project => (
                <div key={project.id} className="project-card-wrapper">
                  <ProjectCard
                    project={project}
                    onView={handleViewProject}
                    onEdit={handleEditProject}
                    onDelete={handleDeleteConfirm}
                  />
                </div>
              ))}
            </div>
          )}
        </div>

        {/* 项目表单 */}
        <ProjectForm
          visible={formVisible}
          onCancel={handleFormCancel}
          onSubmit={handleFormSubmit}
          initialValues={editingProject}
          title={editingProject ? '编辑项目' : '新建项目'}
        />

        {/* 导入模态框 */}
        <ImportModal
          visible={importModalVisible}
          onCancel={() => setImportModalVisible(false)}
          onSuccess={loadProjects}
        />

        {/* 删除确认对话框 */}
        <Modal
          title="确认删除"
          open={!!deletingProject}
          onOk={handleDeleteProject}
          onCancel={() => setDeletingProject(undefined)}
          okText="删除"
          cancelText="取消"
          okButtonProps={{ danger: true }}
          centered
          width={400}
          className="delete-confirm-modal"
        >
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <p style={{ fontSize: '16px', marginBottom: '16px' }}>
              确定要删除项目 <strong style={{ color: '#ff4d4f' }}>{deletingProject?.name}</strong> 吗？
            </p>
            <p style={{ color: '#8c8c8c', fontSize: '14px', margin: 0 }}>
              此操作不可撤销，将同时删除项目下的所有参数分类和参数。
            </p>
          </div>
        </Modal>
      </Content>
    </Layout>
  );
};

export default ProjectList;
